const router = require('koa-router')();
const svgCaptcha = require('svg-captcha');
const fs = require('fs');
const path = require('path');
const jwt = require("jsonwebtoken");
const mykey = 'sefhliefop';

router.get('/code', async (ctx, next) => {
  //利用svg-captcha模块生成验证码
  const img = svgCaptcha.create({
    size: 4,
    ignoreChars: '0o1l',
    color: true,
    noise: 1,//干扰线
    background: '#666',
    height: 50,
    width: 120
  })
  ctx.body = img;
})

//实现登录页面
router.post("/subform", async (ctx, next) => {
  let adminList = await ctx.db.EXCUTE("select * from admins");
  console.log(ctx.request.body);
  let request = ctx.request.body;
  adminList.forEach(item => {
    if (item.account == request.account && item.pass == request.pass) {
      let token = jwt.sign({ "account": item.account }, mykey);
      // console.log(token);
      ctx.body = { "code": 200, "user": { item }, "msg": "ok", "token": token }
    }
  });
})

//验证token
router.get("/getToken", async (ctx, next) => {
  const { token } = ctx.query;
  console.log(token);
  //验证token
  if (token) {
    ctx.body = { "code": 200 }
  } else {
    ctx.body = { "code": 0, "message": "token 不存在" }
  }
})

//图片列表页面的路由
//实现图片上传
router.post("/uploadImage", async (ctx, next) => {
  //保存上传文件的相关信息
  let file = ctx.request.files.file;
  console.log(file);
  const reader = fs.createReadStream(file.filepath)
  let filePath = path.join(__dirname, '../public/images/' + `${file.originalFilename}`);
  const upStream = fs.createWriteStream(filePath)
  reader.pipe(upStream);

  let sql = "insert into images(imgName,imgSize,imgType,imgUrl) values (?,?,?,?)"
  await ctx.db.EXCUTE(sql, [file.originalFilename, file.size, file.mimetype, filePath]);
  ctx.body = { "code": 200, "msg": "上传成功" }
})
//获取图片列表
router.get("/imgList", async (ctx, next) => {
  const { page, size } = ctx.query;
  let imageList = await ctx.db.EXCUTE("select * from images");
  let length = imageList.length;
  const imgPage = imageList.slice(size * (page - 1), size * page);
  ctx.body = { "code": 200, "imgList": imgPage, "length": length };
})
//删除对应图片
router.delete('/delImg:id', async (ctx, next) => {
  const delId = ctx.params.id;
  let sql = "delete from images where imgId=?";
  await ctx.db.EXCUTE(sql, delId);
  ctx.body = { "code": 200, "msg": "删除成功" }
})

//用户列表页面
//获得用户信息
router.get("/userList", async (ctx, next) => {
  const { page, size } = ctx.query;
  let userList = await ctx.db.EXCUTE("select * from user");
  let length = userList.length;
  const userPage = userList.slice(size * (page - 1), size * page);
  console.log(userPage);
  ctx.body = { "code": 200, "userList": userPage, "length": length };
})
//增加用户
router.post("/addUser", async (ctx, next) => {
  const request = ctx.request.body;
  let sql = "insert into user(userName,telephone,email,address) values (?,?,?,?)"
  await ctx.db.EXCUTE(sql, [request.userName, request.telephone, request.email, request.address]);
  let userList = await ctx.db.EXCUTE("select * from user");
  ctx.body = { "code": 200, "userList": userList, "msg": "ok" }
})
//删除指定用户
router.delete("/delUser:id", async (ctx, next) => {
  const delId = ctx.params.id;
  let sql = "delete from user where userId=?";
  await ctx.db.EXCUTE(sql, delId);
  let userList = await ctx.db.EXCUTE("select * from user");
  ctx.body = userList;
})
//修改用户信息
router.post("/changeUser", async (ctx, next) => {
  const { userId, userName, telephone, email, address } = ctx.request.body;
  console.log(email);
  let sql = `update user set userName='${userName}',telephone='${telephone}',email='${email}',address='${address}' where userId='${userId}' `;
  await ctx.db.EXCUTE(sql);
  let userList = await ctx.db.EXCUTE("select * from user");
  ctx.body = { "code": 200, "userList": userList }
})
//查找对应用户
router.get("/searchUser", async (ctx, next) => {
  const { content } = ctx.query;
  let sql = "select * from user where userName=?";
  let result = await ctx.db.EXCUTE(sql, content);
  console.log(result);
  ctx.body = { "code": 200, "userList": result }
})

//物流线路列表
//查询物流路线的信息
router.get("/lineList", async (ctx, next) => {
  const { page, size } = ctx.query;
  let lineList = await ctx.db.EXCUTE("select * from logisticslineManage order by isTop desc");
  let length = lineList.length;
  const linePage = lineList.slice(size * (page - 1), size * page);
  console.log(lineList);
  ctx.body = { "code": 200, "lineList": linePage, "length": length };
})
//增加物流线路
router.post("/addLine", async (ctx, next) => {
  const { lineName, lineWay, lineAddress, telephone } = ctx.request.body;
  let sql = "insert into logisticslineManage(lineName,lineWay,lineAddress,telephone) values (?,?,?,?)"
  await ctx.db.EXCUTE(sql, [lineName, lineWay, lineAddress, telephone]);
  let lineList = await ctx.db.EXCUTE("select * from logisticslineManage");
  ctx.body = { "code": 200, "lineList": lineList, "msg": "ok" }
})
//删除指定的物流线路
router.delete("/delLine:id", async (ctx, next) => {
  const delId = ctx.params.id;
  console.log(delId);
  let sql = "delete from logisticslineManage where lineId=?";
  await ctx.db.EXCUTE(sql, delId);
  let lineList = await ctx.db.EXCUTE("select * from logisticslineManage");
  ctx.body = lineList;
})
//修改物流线路
router.post("/changeLine", async (ctx, next) => {
  const { lineId, lineName, lineWay, lineAddress, telephone } = ctx.request.body;
  let sql = `update logisticslineManage set lineName='${lineName}',lineWay='${lineWay}',lineAddress='${lineAddress}',telephone='${telephone}' where lineId='${lineId}' `;
  await ctx.db.EXCUTE(sql);
  let lineList = await ctx.db.EXCUTE("select * from logisticslineManage");
  ctx.body = { "code": 200, "userList": lineList }
})
//查找目标的物流线路
router.get("/searchLine", async (ctx, next) => {
  const { content } = ctx.query;
  let sql = `select * from logisticslineManage where lineName like'%${content}%'`;
  let result = await ctx.db.EXCUTE(sql);
  console.log(result);
  ctx.body = { "code": 200, "lineList": result }
})
//置顶指定的物流线路
router.get("/topLine:id", async (ctx, next) => {
  const Id = ctx.params.id;
  let sql1 = `update logisticslineManage set isTop='1' where lineId='${Id}'`;
  await ctx.db.EXCUTE(sql1);
  let sql2 = `update logisticslineManage set isTop='0' where lineId!='${Id}'`;
  await ctx.db.EXCUTE(sql2);
  let sql = "select * from logisticslineManage order by isTop DESC";
  let result = await ctx.db.EXCUTE(sql);
  console.log(result);
  ctx.body = { "code": 200, "lineList": result }
})

module.exports = router
